var globalDB;
// Wait for PhoneGap to load

document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready

function onDeviceReady() {
	if (!window.openDatabase) {
		alert('Databases are not supported in this browser.');
	} else {
		globalDB = window
				.openDatabase("pushdb", "1.0", "PhoneGap Demo", 200000);
		globalDB.transaction(populateindexDB, errorCB, successindexCB);

	}

}
// Populate the database

function populateindexDB(tx) {
	tx.executeSql('CREATE TABLE IF NOT EXISTS pushtable (id integer primary key autoincrement,messageId text,companyName text, messageJson text,isRead text)');
	// tx.executeSql('INSERT INTO pushtable (messageId, messageJson ) VALUES
	// ("Second row","2nd row")');
	// alert('Databases populateDB.');
}

// Query the database

function queryDB(tx) {
	tx.executeSql('SELECT * FROM pushtable', [], querySuccess, errorCB);
	// alert('Databases queryDB.');
}
function GetUnique(inputArray) {
	var outputArray = [];

	for ( var i = 0; i < inputArray.length; i++) {
		if ((jQuery.inArray(inputArray[i], outputArray)) == -1) {
			outputArray.push(inputArray[i]);
		}
	}

	return outputArray;
}
// Query the success callback
var selectedComp="";
var selectedId="";
function querySuccess(tx, resultsAll) {
	var all_list = "";
	var json = "";
	var len = resultsAll.rows.length;
	if (len > 0) {
		var compIds = new Array(len);
		for ( var i = 0; i < len; i++) {
			json = JSON.parse(resultsAll.rows.item(i).messageJson);
			compIds[i] = json.companyName;
		}
		var uniqueCompIds = GetUnique(compIds);
		//alert('results uniqueCompIds.' + uniqueCompIds);
		var unreadCount = Array.apply(null, new Array(uniqueCompIds.length))
				.map(Number.prototype.valueOf, 0);

		for ( var i = 0; i < len; i++) {
			var json = JSON.parse(resultsAll.rows.item(i).messageJson);
			for ( var j = 0; j < uniqueCompIds.length; j++) {
				// alert('results (uniqueCompIds[j] == json.companyId)
				// .'+(uniqueCompIds[j] == json.companyId));
				// alert('results results.rows.item(i).isRead.localeCompare("N")
				// .'+results.rows.item(i).isRead.localeCompare("N"));
				if ((uniqueCompIds[j].localeCompare(json.companyName) == 0)
						&& (resultsAll.rows.item(i).isRead.localeCompare("N")) == 0) {
					unreadCount[j] = (unreadCount[j]) + 1;
				}
			}
		}
		//alert('results unreadCount.' + unreadCount);
		for ( var i = 0; i < uniqueCompIds.length; i++) {
			var json = JSON.parse(resultsAll.rows.item(i).messageJson);
			all_list += '<li><a href="#" id="' + i + '" class="info-go">'
					+ uniqueCompIds[i] + ' <span class="ui-li-count">'
					+ unreadCount[i] + '</span></a></li>';
		}

	} else {
		all_list += '<li><a href="#" id="' + 0
				+ '" class="info"> no results </a></li>';
	}

	// set up string for adding <li/>

	// append list to ul
	$("#all_results").append(all_list).promise().done(function() {
		// wait for append to finish - thats why you use a promise()
		// done() will run after append is done
		// add the click event for the redirection to happen to #details-page
		$(this).on("click", ".info-go", function(e) {
			e.preventDefault();
			selectedComp = uniqueCompIds[this.id];
			// store the information in the next page's data
			$("#listpage").data("info", uniqueCompIds[this.id]);
			// change the page # to second page.
			// Now the URL in the address bar will read index.html#details-page
			// where #details-page is the "id" of the second page
			// we're gonna redirect to that now using changePage() method
			// $.mobile.changePage("listpage.html");
			$.mobile.changePage("#listpage", {
				transition : "pop"
			});
		});

		
		$("#listpage").on("pageshow" , function() {
			  showListData();
			});
		// refresh list to enhance its styling.
		$(this).listview("refresh");
	});
}

function showListData(){
	//alert('showListData  :'+showListData);

		globalDB.transaction(populateindexDB, errorCB, successForCompCB);
	//alert('showListData :'+selectedComp);
}
function successForCompCB(){
	//alert('successForCompCB  :'+successForCompCB);

	globalDB.transaction(queryDBForComp, errorCB);
}
function queryDBForComp(tx) {
	//alert('queryDBForComp  :'+queryDBForComp);
	tx.executeSql("SELECT * FROM pushtable WHERE companyName='"+selectedComp+"'", [], querySuccessForCompData, errorCB);
	// alert('Databases queryDB.');
}
function querySuccessForCompData(tx, resultsCompany) {
	var all_list_comp = "";
	var json = "";
	var len = resultsCompany.rows.length;
	//alert('queryDBForComp  :'+queryDBForComp);
	//alert('all_list_comp len :'+all_list_comp);
	//alert('querySuccessForCompData len :'+len);
	for ( var i = 0; i < len; i++) {
		var json = JSON.parse(resultsCompany.rows.item(i).messageJson);
		all_list_comp += '<li><a href="#" id="' + resultsCompany.rows.item(i).id + '" class="info-go">'
				+ json.companyName + ' <span class="ui-li-count">'
				+ resultsCompany.rows.item(i).isRead + '</span></a></li>';
	}
	// append list to ul
	$("#all_results_comp").empty().append(all_list_comp).promise().done(function() {
		// wait for append to finish - thats why you use a promise()
		// done() will run after append is done
		// add the click event for the redirection to happen to #details-page
		$(this).on("click", ".info-go", function(e) {
			selectedId = this.id;
			e.preventDefault();
			// store the information in the next page's data
			$("#all_results_comp").data("info", this.id);
			// change the page # to second page.
			// Now the URL in the address bar will read index.html#details-page
			// where #details-page is the "id" of the second page
			// we're gonna redirect to that now using changePage() method
			// $.mobile.changePage("listpage.html");
			$.mobile.changePage("#listdetailpage", {
				transition : "pop"
			});
		});
		
		
		$("#listdetailpage").on("pageshow" , function() {
			  showListDetailData();
			});
		// refresh list to enhance its styling.
		$(this).listview("refresh");
	});
}

function showListDetailData(){
	//alert('showListData  :'+showListData);

		globalDB.transaction(populateindexDB, errorCB, successForCompDetailsCB);
	//alert('showListData :'+selectedComp);
}

function successForCompDetailsCB(){
	
	globalDB.transaction(queryDBForCompDetails, errorCB);

}
function queryDBForCompDetails(tx) {
	//alert('selectedId  :'+selectedId);
	//alert("SELECT * FROM pushtable WHERE id="+selectedId);

	tx.executeSql("SELECT * FROM pushtable WHERE id="+selectedId, [], querySuccessForCompDetailsData, errorCB);
	// alert('Databases queryDB.');
}

function querySuccessForCompDetailsData(tx, resultsCompanyDetails) {
	//alert('resultsCompanyDetails  :'+resultsCompanyDetails);

	var all_list_comp_data = "";
	var json = "";
	//var len = resultsCompanyDetails.rows.length;
	var json = JSON.parse(resultsCompanyDetails.rows.item(0).messageJson);
	$("#listdetailpageimage").attr("src", "goa_beach.jpg")
	$("#listdetailpagecompany").text( ""+json.companyName );
	$("#listdetailpageoffer").text( ""+json.message_title );
	$("#listdetailpagevalidity").text( ""+json.messageValidTillDate );
}
// Transaction error callback
function errorCB(err) {
	alert("Error processing SQL: " + err.code);
}

// Transaction success callback

function successindexCB() {
	globalDB.transaction(queryDB, errorCB);
	//alert('Databases successindexCB.');
}
